<script setup lang="ts">
import { reason,org_code } from "@/utils";
import { StarFilled,CirclePlusFilled,Delete } from "@element-plus/icons-vue";
import {  computed, ref } from "vue";
import DataGrid from "./DataGridApply.vue";
import ButtonCo from "./buttons/ButtonCo.vue";
import { dayjs, ElMessage,ElMessageBox } from "element-plus";
import { applySend,segmentCheck } from "@/api/apply";
import * as XLSX from "xlsx"
import { unit } from "@/utils/product";
import type { UploadProps } from "element-plus";

//提交表單時的類型
export interface ApplyForm {
  apply_date: string;
  applier: string;
  org_code: string;
}
//添加一條數據的類型
export interface ApplyFormitem {
  material_originA: string;
  material_replaceA: string;
  material_product: string;
  replace_reason: string;
  comments: string;
  unit: string;
  amount: number;
  start_time: string;
}

//料號描述-description
const segmentDescription = ref<string[]>([])
//原料號輸入框
const material_product_item = ref("")

//提示框
const centerDialogVisible = ref(false);
const selectorg_code = ref(false);
//料號檢查
const segmentcheckFlag = ref(false)
const segmentcheckFlagReplace = ref(false)
//發送請求帶入信息
const applyform = ref<ApplyForm>({
  apply_date: "",
  applier: "",
  org_code: "",
});
//輸入框信息記錄
const applyformitem = ref<ApplyFormitem>({
  material_originA: "",
  material_replaceA: "",
  material_product: "",
  replace_reason: "",
  comments: "",
  unit: "",
  amount: 0,
  start_time: ""
});
//表格信息記錄
const applyformitems = ref<ApplyFormitem[]>([]);

//往表格內添加一行數據
function addOne() {
  if (
    applyformitem.value.material_originA === "" ||
    applyformitem.value.material_replaceA === "" ||
    applyformitem.value.material_product === "" ||
    applyformitem.value.replace_reason === "" || 
    applyformitem.value.unit === "" ||
    applyformitem.value.amount <= 0 ||
    applyformitem.value.start_time === ""
  ) 
  {
    ElMessage.error("填寫數據不能為空");
  }
  else if(!segmentcheckFlag.value || !segmentcheckFlagReplace.value){
    ElMessage.error("原料號或替代料號不正確，請檢查")
  }
  else if(applyformitem.value.material_originA === applyformitem.value.material_replaceA){
    ElMessage.error("原料號與替代料號相同，請檢查!")
  }
  else {
    if (
      applyformitems.value.some(
        (item1) =>
          item1.material_originA === applyformitem.value.material_originA &&
          item1.material_replaceA === applyformitem.value.material_replaceA &&
          item1.material_product === applyformitem.value.material_product
      )
    ) {
      centerDialogVisible.value = true;
    } else {
      let item = {...applyformitem.value}
      item.start_time =  dayjs(item.start_time).format("YYYY-MM-DD")
      applyformitems.value.push(item);
      clear();
      ElMessage.success("添加成功");
    }
  }
}
//清空輸入框
function clear(){
  applyformitem.value.material_originA = '';
  applyformitem.value.material_replaceA = '';
  applyformitem.value.material_product = '';
  applyformitem.value.replace_reason = '';
  applyformitem.value.unit = '',
  applyformitem.value.amount = 0,
  applyformitem.value.start_time = "",
  applyformitem.value.comments = '';
  segmentDescription.value = []
}
//
function confirm(param: number) {
  centerDialogVisible.value = false
  if (param === 1) {
    let item:ApplyFormitem = applyformitem.value
    applyformitems.value.push(item);
    clear();
    ElMessage.success('添加成功')
    return true
  }
  else{
    return false
  }
}
//確定送出後帶出廠區選擇
function confirm_org(param: number){
  selectorg_code.value = false;
  if(param === 1){
    save()
  }
  else{
    return false
  }
}
//刪除一行表格的數據
function deletRow(index:number){
  applyformitems.value.splice(index,1)
  ElMessage.success('刪除成功')
}

//發送數據到後台,送出
function save(){
  //檢查
  if(applyformitems.value.length === 0){
    ElMessage.error('請至少先新增一筆數據成功後再送出!')
    return false
  }
  let username = localStorage.getItem("username")?.toString();
  applyform.value.apply_date = Date.now().toLocaleString();
  if (username !== undefined) {
    applyform.value.applier = username;
  }
  else{
    ElMessage.error('未檢測到用戶！請重新登錄');
    return false
  }

  //發送請求
  let obj:Array<any> = [];
  applyformitems.value.forEach(item => {
    let objitem = {
      "material_originA":item.material_originA,
      "material_replaceA":item.material_replaceA,
      "material_product":item.material_product,
      "replace_reason":item.replace_reason,
      "comments":item.comments,
      "unit":item.unit,
      "amount":item.amount,
      "start_time":item.start_time,
      "applier":applyform.value.applier,
      "org_code":applyform.value.org_code
    }
    obj.push(objitem)
  });
  applySend(JSON.stringify(obj)).then((res)=>{
    if(res){
      ElMessage.success('申請成功')
      setTimeout(() => {
        location.reload()
      }, 500);
    }
  })

}

//料號檢查
function segmentcheck (type:string){
  if(type === 'A' && applyformitem.value.material_originA !== ""){
    segmentCheck(applyformitem.value.material_originA).then((res:any)=>{
      if(res[0].count_flag === undefined){
        ElMessage.error("輸入原料號錯誤")
        segmentcheckFlag.value = false;
      }
      else{
        segmentcheckFlag.value = true;
        segmentDescription.value[0] = res[0].description;
      }
    })
  }
  else if(type === 'R' && applyformitem.value.material_replaceA !== ""){
    segmentCheck(applyformitem.value.material_replaceA).then((res:any)=>{
      if(res[0].count_flag == undefined){
        ElMessage.error("輸入替代料號錯誤")
        segmentcheckFlagReplace.value = false;
      }
      else{
        segmentcheckFlagReplace.value = true;
        segmentDescription.value[1] = res[0].description;
      }
    })
  }
}

//添加原料號
function setMaterial_Product(item:string){
  //判斷是否輸入非法字符空格、逗號
  if(applyformitem.value.material_product.length > 2000){
    ElMessage.error(`錯誤成品號：${item}--成品料號過長，無法輸入`)
    return false
  }
  else if(applyformitem.value.material_product.split(',').some(item1=>item1===item)){
    ElMessage.error(`錯誤成品號：${item}--已有輸入此料號，請檢查！`)
    return false
  }
  else if(item.includes(" ") || item.includes(",")){
    ElMessage.error(`錯誤成品號：${item}--請勿輸入非法字符空格或者逗號`)
    return false
  }
  else if(item.length !==3 && item.length !==7 && item.length !==10){
    ElMessage.error(`錯誤成品號：${item}--請輸入3碼、7碼或10碼`)
    return false
  }
  else{
    if(applyformitem.value.material_product === ""){
      applyformitem.value.material_product = item
    }
    else{
      applyformitem.value.material_product += `,${item}`
    }
    material_product_item.value = ""
  }
}

//上傳EXCEL檔
const handleExceed : UploadProps['onChange'] = (file:any)=>{
  const reader = new FileReader();
  reader.onload = (e) => {
    let data:Uint8Array
    if(e.target?.result !== undefined && e.target.result !== null && typeof(e.target.result) !== "string"){
      data = new Uint8Array(e.target?.result);
    }
    else{
      data = new Uint8Array()
    }
    const workbook = XLSX.read(data, { type: 'array' });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);
    if(jsonData.length > 0){
      if(jsonData[0]['成品料號']){
        applyformitem.value.material_product = ""
        jsonData.forEach((item:any) => {
        setMaterial_Product(item['成品料號'].toString())
      });
      ElMessage.success('上傳Excel檔成功')
      } else{
        ElMessage.error("請確保xlsx檔中含有‘成品料號’一列")    
      }
    }
    else{
      ElMessage.error('未獲取到成品料號數據')
      return false
    }
  };
  reader.readAsArrayBuffer(file.raw);
}
//清空成品號
function clearProduct(){
  if(applyformitem.value.material_product.length > 0){
    ElMessageBox.confirm(
    '確定要清空所有成品料號嗎？',
    '警告',
    {
      confirmButtonText: '確定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      applyformitem.value.material_product = ""
      ElMessage({
        type: 'success',
        message: '成功清空',
      })
    }).catch(()=>{return false})
  }
}
//已添加成品料號記錄
const alreadyToProduct = computed(()=>{
  return applyformitem.value.material_product.split(",")
})
</script>

<template>
  <div class="input-box1">
    <el-row class="row">
      <el-col :span="12">
        <!-- 原料 -->
        <span class="row-text">物料原料號A</span>
        <el-input
          class="row-input"
          v-model.trim="applyformitem.material_originA"
          style="width: 230px; height: 32px"
          placeholder="請輸入"
          @change="segmentcheck('A')"
        />
      </el-col>
      <el-col :span="12">
        <!-- 替代料 -->
        <span class="row-text">物料替代料號B</span>
        <el-input
          class="row-input"
          v-model.trim="applyformitem.material_replaceA"
          style="width: 230px; height: 32px"
          placeholder="請輸入"
          @change="segmentcheck('R')"
        />
      </el-col>
    </el-row>
    <el-row class="row-description">
      <span size="small" class="description">{{ segmentDescription[0] }}</span>
      <span size="small" class="description">{{ segmentDescription[1] }}</span>
    </el-row>
    <el-row class="row">
      <!-- 成品料號 -->
      <el-col :span="12">
        <span class="row-text">對應成品料號</span>
        <el-button style="float: right;"  type="primary" :icon="Delete" @click="clearProduct"></el-button>
        <el-upload :auto-upload="false" :on-change="handleExceed" accept=".xls,.xlsx"
        :show-file-list = "false"
        style="float: right;margin-right: 10px">
          <el-button  type="primary" :icon="CirclePlusFilled"></el-button>
        </el-upload>
        <el-popover title="已輸入對應成品料號" :width="200"  effect="dark" trigger="hover">
          <template #reference>
            <el-input
            class="row-input"
            v-model="material_product_item"
            style="width: 128px; height: 32px"
            :placeholder="applyformitem.material_product === ''?'請輸入':'繼續輸入'"
            @keyup.enter="setMaterial_Product(material_product_item)"
            />
          </template>
          <el-scrollbar max-height="400px">
            <el-text class="product_item" v-for="list in alreadyToProduct" :key="list">{{ list }}</el-text>
          </el-scrollbar>
        </el-popover>
      </el-col>
      <el-col :span="12">
        <!-- 替代原因 -->
        <span class="row-text">替代原因</span>
        <el-select
          class="row-input"
          v-model="applyformitem.replace_reason"
          placeholder="請選擇"
          style="width: 230px"
        >
          <el-option v-for="item in reason" :key="item.code" :value="item.desc">
          </el-option>
        </el-select>
      </el-col>
    </el-row>
    <el-row class="row-description">
      <span size="small" class="description">使用Enter 鍵入或者按鈕添加excel檔</span>
    </el-row>
    <el-row class="row">
      <!-- 單位 -->
      <el-col :span="12">
        <span class="row-text">單位</span>
        <el-select
          class="row-input"
          v-model="applyformitem.unit"
          placeholder="請選擇"
          style="width: 230px"
        >
          <el-option v-for="item in unit" :key="item.code" :value="item.unit">
          </el-option>
        </el-select>
      </el-col>
      <!-- 數量 -->
       <el-col :span="12">
          <span class="row-text">數量</span>
          <el-input-number class="row-input" v-model="applyformitem.amount" size="small" style="width: 230px; height: 32px" :min="0"></el-input-number>
       </el-col>
    </el-row>
    <el-row class="row-description">
      <span size="small" class="description"></span>
    </el-row>
    <el-row class="row">
      <!-- 開始日期 -->
      <el-col :span="12">
        <span class="row-text">開始日期</span>
        <el-date-picker class="row-input"  v-model="applyformitem.start_time" size="small" style="width: 230px; height: 32px"></el-date-picker>
      </el-col>
      <!-- 備註 -->
      <el-col :span="12">
        <span class="row-text">備註</span>
        <el-input
          class="row-input"
          v-model="applyformitem.comments"
          :rows="1"
          type="textarea"
          style="width: 230px"
          placeholder="請輸入"
        />
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <ButtonCo @click="addOne" text="新增" />
      </el-col>
      <el-col :span="12">
        <ButtonCo @click="()=>selectorg_code=true" text="送出" />
      </el-col>
    </el-row>
  </div>
  <el-divider>
    <el-icon><star-filled /></el-icon>
  </el-divider>
  <DataGrid :applyformitems="applyformitems" isapply="true" @deleteRow="deletRow"></DataGrid>
  <el-dialog
    v-model="centerDialogVisible"
    title="警告"
    width="500"
    align-center
  >
    <span>已有相同的記錄，您確定是否添加相同的資料</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="confirm(2)">取消</el-button>
        <el-button type="primary" @click="confirm(1)">
          確認
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="selectorg_code"
    title="提示"
    width="350"
    align-center
  >
    <span>請選擇廠區送出</span>
    <template #footer>
      <div class="dialog-footer">
        <el-select v-model="applyform.org_code" style="margin-bottom: 20px;">
          <el-option v-for="list in org_code" :key="list.code" :value="list.value"></el-option>
        </el-select>
        <el-button @click="confirm_org(2)">取消</el-button>
        <el-button type="primary" @click="confirm_org(1)">
          確認
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style>
.input-box1 {
  width: 820px;
  margin: 0 auto;
  padding-top: 20px;
  height: auto;
  /* font-family: "Courier New", Courier, monospace; */
  line-height: 32px;
  /* overflow: hidden; */
}
.el-col .row-text {
  width: 110px;
  height: 32px;
  text-align: right;
  /* display: inline-block; */
  padding-left: 20px;
  float: left;
  line-height: 32px;
  /* margin-top: 20px; */
}
.input-box1 .el-col,
.input-box2 .el-col {
  margin-top: 15px;
}
.row-input {
  float: right;
  margin-right: 20px;
}
.description{
  font-size: 10px;
  height: 12px;
  display: inline-block;
  color: rgb(179, 41, 41);
  text-align: right;
  width: 45%;
  padding-right: 5%;
}
.product_item{
  background-color: rgba(240, 237, 237, 0.8);
  display: block;
  margin-top: 2px;
  text-align: center;
}
 

</style>
